import { useState,useEffect } from "react";
import {FetchService} from "@/utils/request";
import Ctable from "@/components/commonTable";
import {resType} from "@/commonType";
import {dateFormat} from "@/utils/index";
import { UploadOutlined } from '@ant-design/icons';
import { Pagination,Modal,Button,Form,Image,DatePicker,Input,Select,InputNumber,message} from "antd";
import DynamicFormModal from '@/components/commonDialog';
import type { TableProps,UploadProps } from 'antd';
type TablePagination<T extends object> = NonNullable<Exclude<TableProps<T>['pagination'], boolean>>;
type TablePaginationPosition<T extends object> = NonNullable<
  TablePagination<T>['position']
>[number];
const fetchService = new FetchService();

type DataType = {
    id: number;
    product_sku__id: string;
    name: string;
    user_id: string;
    username: string;
    total_price:number;
    description: string;
    likes_count:number;
    favorites_count: string;
    views_count: string;
    status: string;
    img_url:string;
    create_at:Date;
    update_at:Date;
    is_public:string;

}

const addProductOpts = [
    {
        name:"产品名称",
        key:"name",
        component:"input",
        span:12,
        required:true
    },
    {
        name:"用户",
        key:"user_id",
        component:"select",
        items:[],
        span:12,
        required:true
    },
      {
        name:"用户名",
        key:"username",
        component:"input",
        disabled:true,
        span:12,
        required:true
    },
    {
        name:"缩略图",
        key:"img_url",
        component:"upload",
        span:12,
        required:false
    },
    {
        name:"点赞数",
        key:"likes_count",
        component:"input",
        span:12,
        required:false
    },
    {
        name:"收藏数",
        key:"favorites_count",
        component:"input",
        span:12,
        required:false
    },
    {
        name:"浏览量",
        key:"views_count",
        component:"input",
        span:12,
        required:false
    },
    {
        name:"总价",
        key:"total_price",
        component:"input",
        span:12,
        required:false
    },
    {
        name:"是否公开",
        key:"is_public",
        component:"select",
        items:[
          {label:"是",value:"1"},
          {label:"否",value:"0"}
        ],
        span:12,
        required:true
    },
    {
        name:"状态",
        key:"status",
        component:"select",
        items:[
          {label:"上架",value:"1"},
          {label:"下架",value:"0"}
        ],
        span:12,
        required:false
    }, 
    {
      name:"描述",
      key:"description",
      component:"textarea",
      span:24,
      required:false
    }
  ]


  type DataTypeMaterial = {
    id: number;
    name:string;
    category:string;//0：绳子  1：珠子  2：配饰  3：其他
    image_url:string;
    stock: number;//库存数量,用户下单后更新库存
    buying_price: number;//采购价格
    selling_price: number;//销售价格
    description: string;
    diameter: number;//直径
    length: number;//长度
    material:string;//材质
    color:string;//颜色
    manufacturer:string; //制造商
    origin:string; //产地
    weight:number; //重量
    status:string; //状态 0：上架  1：下架
    create_at:Date;
    update_at: Date;
}


const uploadProps: UploadProps = {
    name: 'file',
    action: 'https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload',
    headers: {
      authorization: 'authorization-text',
    },
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
    },
  };

  

//findProduct
const Product:React.FC = () => {
    const [tableData,setTableData] = useState<any[]>([]);
        const [page,setPage] = useState({pageNum:1,pageSize:10});
        const [total,setTotal] = useState<number>(0);
        const [user,setUser] = useState<any>([]);
        const [addform,setAddForm] = useState<any>({userid:'',name:"",description:'',img_url:"",total_price:0,is_public:"1"});
        const [form] = Form.useForm();
        const [addModelTitle,setAddModelTitle] = useState<string>("新增产品");
        const [addModelVisible,setAddModelVisible] = useState<boolean>(false);
        const [bottom, setBottom] = useState<TablePaginationPosition<DataType>>('bottomRight');
        type SizeType = Parameters<typeof Form>[0]['size'];
        const [componentSize, setComponentSize] = useState<SizeType | 'default'>('default');
        const [addDialogVisible, setAddDialogVisible] = useState(false);
        const [dialogTitle, setDialogTitle] = useState("编辑")
        const [currentRowId, setCurrentRowId] = useState<number | null>(null);
        const [synthesisDialogVisible,setSynthesisDialogVisible] = useState<boolean>(false);
        const [tableDataMaterial,setTableDataMaterial] = useState<any[]>([]);
        const [materialTotal,setMaterialTotal] = useState<number>(0);
        const [materialQuantities, setMaterialQuantities] = useState<Record<number, number>>({});
        const materialCols = [
          {
            title: '物料名称',
            dataIndex: 'name',
            key: 'name',
            width:120,
            searchable: true,
          },
          {
            title: '类型',
            dataIndex: 'category',
            width:120,
            key: 'category',
            searchable: true,
            render: (text:string) => {
              return text == '0' ? "绳子" : text == '1' ? "珠子" : text == '2' ? "配饰" : "其他"
            }
          },
          {
            title: '预览图',
            dataIndex: 'image_url',
            key: 'image_url',
            width:120,
            render: (text:string) => {
              if(!text) return <div>暂无图片</div>
              return <Image
                        width={100}
                        src={"http://localhost:3000/" + text}
                      />
            },
          },
          {
            title: '库存',
            dataIndex: 'stock',
            key: 'stock',
            width:100,
            searchable: true,
          },
          {
            title: '采购价格（元）',
            width:120,
            dataIndex: 'buying_price',
            key: 'buying_price',
            searchable: true,
          },
          {
            title: '销售价格（元）',
            width:120,
            dataIndex: 'selling_price',
            key: 'selling_price',
            searchable: true,
          },
          {
            title: '直径（mm）',
            width:100,
            dataIndex: 'diameter',
            key: 'diameter',
          },
          {
            title: '长度（mm）',
            width:100,
            dataIndex: 'length',
            key: 'length',
          },
          {
            title: '材质',
            width:100,
            dataIndex: 'material',
            key: 'material',
          },
          {
            title: '颜色',
            width:100,
            dataIndex: 'color',
            key: 'color',
          },
          {
            title: '制造商',
            width:120,
            dataIndex: 'manufacturer',
            key: 'manufacturer',
          },
          {
            title: '产地',
            width:130,
            dataIndex: 'origin',
            key: 'origin',
          },
          {
            title: '质量（g）',
            width:100,
            dataIndex: 'weight',
            key: 'weight',
          },
          {
            title: '入库时间',
            dataIndex: 'create_at',
            width:120,
            key: 'create_at',
            searchable: true,
          },
          {
            title: '修改时间',
            dataIndex: 'update_at',
            width:120,
            key: 'update_at',
          },
          {
            title: '状态',
            dataIndex: 'status',
            width:90,
            key: 'status',
            render: (text:string) => {
              console.log(text,'text');
              return text == '0' ? "下架" : text == '1'?'上架':'废弃';
            }
          },
          {
            title: '描述',
            dataIndex: 'description',
            width:150,
            key: 'description',
          },
          {
            title: '数量',
            dataIndex: 'quantity',
            key: 'quantity',
            width: 100,
            render: (text: string, record: any) => (
              <InputNumber
                min={0}
                defaultValue={0}
                onChange={(value) => handleQuantityChange(record.id, value)}
              />
            ),
          },
        ];
        const [formData, setFormData] = useState<any>({
            name:"",
            user_id:"",
            username: "",
            total_price:0,
            description: 0,
            likes_count:0,
            favorites_count:"",
            views_count:"",
            status: "",
            img_url:"",
            create_at:"",
            update_at:"",
            is_public:"",
            id:null
        });
        const onFormLayoutChange = ({ size }: { size: SizeType }) => {
            setComponentSize(size);
        };
        const getUsers = async ()=>{
            let res:resType = await fetchService.get("/wechat/findUser");
            if(res.code === 200) {
                setUser(res.data)
                addProductOpts[1].items = res.data.map((item:any)=>{return {label:item.nickname,value:item.open_id}})

            }
        }
        const handleQuantityChange = (id: number, value: number) => {
          setMaterialQuantities((prev) => ({
            ...prev,
            [id]: value,
          }));
        };
        const getMaterialList = async () => {
              let res:resType = await fetchService.get("/product/findMaterial",page);
                if(res.code === 200) {
                  let tdata:any = [];
                  res.data.data.map((item:DataTypeMaterial) => {
                    tdata.push({
                        id: item.id,
                        name:item.name,
                        category:item.category,//0：绳子  1：珠子  2：配饰  3：其他
                        image_url:item.image_url,
                        stock: item.stock,//库存数量,用户下单后更新库存
                        buying_price: item.buying_price,//采购价格
                        selling_price: item.selling_price,//销售价格
                        description: item.description,
                        diameter: item.diameter,//直径
                        length: item.length,//长度
                        material:item.material,//材质
                        color:item.color,//颜色
                        manufacturer:item.manufacturer, //制造商
                        origin:item.origin, //产地
                        weight:item.weight, //重量
                        create_at:item.create_at,
                        update_at: item.update_at,
                        status:item.status,//0：下架  1：上架 2：废弃
                    })
                  })
                  setMaterialTotal(res.data.total)
                  setTableDataMaterial(tdata);
                }
            }
        const columns = [
            {
                title: '名称',
                dataIndex: 'name',
                key: 'name',
            },
            {
                title: '产品SKU',
                dataIndex: 'product_sku__id',
                key: 'product_sku__id',
            },
            {
              title: '用户',
              dataIndex: 'username',
              key: 'username',
              searchable: true,
            },
            {
              title: '总价（元）',
              dataIndex: 'total_price',
              key: 'total_price',
            },
            {
              title: '缩略图',
              dataIndex: 'img_url',
              key: 'img_url',
            },
            {
              title: '点赞数',
              dataIndex: 'likes_count',
              key: 'likes_count',
            },
            {
                title: '收藏数',
                dataIndex: 'favorites_count',
                key: 'favorites_count',
            },
            {
                title: '浏览量',
                dataIndex: 'views_count',
                key: 'views_count',
            },
            {   
                title: '状态',
                dataIndex: 'status',
                key: 'status',
                render: (text:string) => {
                    return text === '1' ? "正常" : "禁用";
                }
            },
            {
                title: '是否公开',
                dataIndex: 'is_public',
                key: 'is_public',
                render: (text:string) => {
                    return text === '1' ? "是" : "否";
                }
            },
            {
                title: '创建时间',
                dataIndex: 'create_at',
                key: 'create_at',
                render: (text:string) => {
                    return dateFormat(text);
                }
            },
            {
                title: '更新时间',
                dataIndex: 'update_at',
                key: 'update_at',
                render: (text:string) => {
                    return dateFormat(text);
                }
            },
            {
                title: '操作',
                dataIndex: 'op',
                key: 'op',
                width:300,
                render: (text:string,record:DataType) => {
                    return <div>
                        <Button type="primary" onClick={() => editProduct(record)}>编辑</Button>
                        <Button style={{marginRight:10,marginLeft:10}} type="primary" onClick={() => synthesis(record)}>物料配置</Button>
                        <Button onClick={() => deleteProduct(record.id)}>删除</Button>
                    </div>;
                }
            }
        ];

       
        const getProduct = async () => {
            let res:resType = await fetchService.get("/product/findProduct",page);
            if(res.code === 200) {
              let tdata:any = [];
              res.data.data.map((item:DataType) => {
                tdata.push({
                    id: item.id,
                    product_sku__id:item.product_sku__id,
                    name:item.name,
                    user_id:item.user_id,
                    username:item.username,
                    total_price:item.total_price,
                    description:item.description,
                    likes_count:item.likes_count,
                    favorites_count:item.favorites_count,
                    views_count:item.views_count,
                    status:item.status,
                    img_url:item.img_url,
                    create_at:item.create_at,
                    update_at:item.update_at,
                    is_public:item.is_public
                })
              })
              setTotal(res.data.total)
              setTableData(tdata);
            }
        }
      
        useEffect(()=>{
            getProduct();
        },[])
        useEffect(()=>{
          getMaterialList();
        },[]);
        useEffect(()=>{
            getUsers();
        },[])
        const search = (info:any)=>{
            console.log(info);
            getProduct();
        }
    
        const addProduct = () => {
            setAddDialogVisible(true)
        }
        const synthesis = (record:DataType)=>{
            setCurrentRowId(record.id)
            setSynthesisDialogVisible(true)
        }
        const editProduct = (record:DataType) => {
            setCurrentRowId(record.id)
            setFormData(record)
            setAddDialogVisible(true)
        }
        const handleAddOk = () => {
            form
            .validateFields()
            .then((values) => {
                // 在这里可以获取到表单的所有字段值
                console.log('Form values:', values);

                // 你可以在这里处理表单数据，比如发送到后端
                // 例如：submitFormData(values);

                // 关闭模态框
                setAddModelVisible(false);
            })
            .catch((errorInfo) => {
                // 如果表单验证失败，会在这里捕获错误
                console.log('Validation failed:', errorInfo);
            });
            //setAddModelVisible(false);
        }
        const handleAddFinish = (values:any)=>{
            console.log(values,'value')
        }
        const handleAddCancel = () => {
            setAddModelVisible(false);
        }
        const editMaterial = (row:any)=>{
          console.log(row,'row')
          setCurrentRowId(row.id)
          setFormData(row)
          setAddDialogVisible(true)
        
        }
          const deleteProduct = async (id:number)=>{
            console.log(id)
            let res:resType = await fetchService.post("/product/removeProduct",[id]);
            if(res.code === 200) {
              message.success("删除成功")
              getProduct();
            }else{
              message.error(res.msg)
            }
          }
          const addMaterial = ()=>{
            setAddDialogVisible(true)
          }
      
          const handleSave = async (form:any)=>{
            console.log(form)
            if(!form.total_price || form.total_price == ""){
              form.total_price = 0;
            }
            if(!form.favorites_count || form.favorites_count == ""){
              form.favorites_count = 0;
            }
            if(!form.likes_count || form.likes_count == ""){
              form.likes_count = 0;
            }
            if(!form.views_count || form.views_count == ""){
              form.views_count = 0;
            }
            form.favorites_count = Number(form.favorites_count);
            form.total_price = Number(form.total_price);
            form.views_count = Number(form.views_count);
            form.likes_count = Number(form.likes_count);
            if(currentRowId){
              form.id = currentRowId;
              let res:resType = await fetchService.post("/product/updateProduct",form);
              if(res.code === 200) {
                message.success("更新成功")
                getProduct()
                setAddDialogVisible(false)
              }
            }else{
              let res:resType = await fetchService.post("/product/addProduct",form);
              if(res.code === 200) {
                message.success("添加成功")
                getProduct();
              }else{
                message.error(res.msg)
                setAddDialogVisible(false)
              }
            }
           
          }
      
          const handleChange = (changeItem:any,items:any)=>{
            console.log(changeItem)
            console.log(items)
            let key = Object.keys(changeItem)[0];
            if(key == "user_id"){
              let userid = items.user_id;
              user.map((item:any)=>{
                if(item.opon_id == userid){
                  setFormData({
                    username:item.nickname
                  })
                }
              })
            }
          }
        // const handleMaterialOk = ()=>{
          
        // }
        const handleMaterialCancel = ()=>{
          setSynthesisDialogVisible(false)
        }
        const selectedRow = (rows:[])=>{
          console.log(rows,'out')
        }
        const handleMaterialOk = () => {
          setSynthesisDialogVisible(true)
          let totalPrice = 0;
          const selectedMaterials = tableDataMaterial.filter((material) => materialQuantities[material.id] > 0);
        
          selectedMaterials.forEach((material) => {
            totalPrice += material.selling_price * materialQuantities[material.id];
          });
        
          const payload = {
            productId: currentRowId,
            materials: selectedMaterials.map((material) => ({
              materialId: material.id,
              quantity: materialQuantities[material.id],
            })),
            totalPrice,
          };
          console.log(payload);
        };
    return  <div>
                <Ctable
                    dataSource={tableData}
                    columns={columns}
                    pagination={{
                    onChange:(page:number) => {
                        setPage({pageNum:page,pageSize:10});
                        getProduct();
                    },
                    total:total,
                    position:[bottom]
                    }}
                    role={["add","edit","delete"]}
                    searchable={true}
                    rowKey="id"
                    search={(info)=>{search(info)}}
                    add={()=>{addProduct()}}
                />
                <DynamicFormModal
                visible={addDialogVisible}
                onCancel={() => setAddDialogVisible(false)}
                formConfig={addProductOpts}
                onSave={handleSave}
                onChange={handleChange}
                formData={formData}
                modalWidth={800}
                title={dialogTitle}
                />
                <Modal width={1200} title="物料配置" open={synthesisDialogVisible} onOk={handleMaterialOk} onCancel={handleMaterialCancel}>
                  <div className="top">
                    <Ctable
                      dataSource={tableDataMaterial}
                      columns={materialCols}
                      pagination={{
                        onChange: (page: number) => {
                          setPage({ pageNum: page, pageSize: 10 });
                          getMaterialList();
                        },
                        total: materialTotal,
                        position: [bottom]
                      }}
                      role={["add", "edit", "delete"]}
                      searchable={false}
                      rowKey="id"
                      search={(info) => { search(info) }}
                      add={() => { }}
                      selected={(rows) => { selectedRow(rows) }}
                    />
                  </div>
                </Modal>
            </div>
}
export default Product;